package com.hxm.demo.netty.simple_demo;

import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPipeline;

import java.util.Objects;

public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    private static final String CHECK = "xiaoming";
    private static final String SECCUSS = "How are xiaoming?$_";
    private static final String ERROR = "bad order$_";

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        System.out.println("服务器读取线程 " + Thread.currentThread().getName() + " channle =" + ctx.channel());
        System.out.println("server ctx =" + ctx);
        System.out.println("看看channel 和 pipeline的关系");
        Channel channel = ctx.channel();
        ChannelPipeline pipeline = ctx.pipeline(); //本质是一个双向链接, 出站入站

        System.out.println("客户端发送消息是:" + msg);
        System.out.println("客户端地址:" + channel.remoteAddress());
        if (Objects.equals(CHECK,msg)){
            //将数据写入到缓存，并刷新
            ctx.writeAndFlush(Unpooled.copiedBuffer(SECCUSS.getBytes()));
        } else {
            ctx.writeAndFlush(Unpooled.copiedBuffer(ERROR.getBytes()));
        }

    }


    //处理异常, 一般是需要关闭通道
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
